package com.fxhy.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baby.constants.Constants;
import com.fxhy.bean.VerifyCode;
import com.fxhy.service.VerifyCodeService;
import com.fxhy.utils.DateUtils;
import com.fxhy.utils.JWTUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.thoughtworks.xstream.core.util.Base64Encoder;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;


/**
 * 验证码
 * @author lifengyao
 *
 */
@Controller
@Api(value="验证码接口")
@Slf4j
public class VerifyCodeApi {
	@Autowired
	DefaultKaptcha defaultKaptcha;
	
	@Autowired
	private VerifyCodeService kaptchaService;
	
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="getVerifyCode",method= {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public  Map getVrifyCode() throws Exception {
		// 生成文字验证码
		String text = defaultKaptcha.createText();
		// 生成图片验证码
		ByteArrayOutputStream outputStream = null;
		BufferedImage image = defaultKaptcha.createImage(text);

		outputStream = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", outputStream);

		// 对字节数组Base64编码
		Base64Encoder encoder = new Base64Encoder();

		// 生成captcha的token
		VerifyCode kaptchaCode = new VerifyCode();
		kaptchaCode.setVerifyCode(text);
		String token = JWTUtil.sign(text, Constants.KAPTCHA_KEY);
		kaptchaCode.setToken(token);
		kaptchaCode.setCreateTime(DateUtils.getNowDate());
		kaptchaCode.setCreateUser("sys");
		String imgStr = encoder.encode(outputStream.toByteArray());
		kaptchaCode.setBase64ImgStr(encoder.encode(outputStream.toByteArray()));
		kaptchaCode = kaptchaService.saveKaptcha(kaptchaCode);
		Map resultMap = new HashMap();
		resultMap.put("token", token);
		resultMap.put("imgStr", "data:image/jpeg;base64,"+imgStr);
		return resultMap;
	}
}
